package com.codeoss.framework.pagebean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.view.clientscript.ClientPageOpenClickScript;
import com.codeoss.framework.view.pagebean.ListViewPageBean;
import com.codeoss.module.ir.model.IrModel;
import com.codeoss.module.ir.service.IIrModelService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
public class ModelListPagePageBean extends ListViewPageBean {
	@Autowired
	private IIrModelService irModelService;
	public void doDesign() {
		YunContext yunContext=YunContext.getCurrentContext();
		yunContext.setRenderCompleted(true);
		List<Long> idList=getSelectedKeyValueList();
		if(idList==null || idList.size()==0) {
			throw new RuntimeException("请选择项");
		}
		IrModel irModel=irModelService.getById(idList.get(0));
		ClientPageOpenClickScript clientPageOpenClickScript=new ClientPageOpenClickScript();
		yunContext.addClientScript(clientPageOpenClickScript);
		clientPageOpenClickScript.setName(irModel.getName());
		clientPageOpenClickScript.setPageCode("model-form-page");
		clientPageOpenClickScript.setEnv(ClientPageOpenClickScript.ENV_DEV);
		Map<String,Object> paraMap=new HashMap<String,Object>();
		clientPageOpenClickScript.setParaMap(paraMap);
		paraMap.put("tableName", irModel.getTableName());
		
	}
	
	public void dataCopy(Map<String,Object> paraMap) {
		YunContext yunContext=YunContext.getCurrentContext();
		yunContext.setRenderCompleted(true);
		List<Long> idList=getSelectedKeyValueList();
		if(idList==null || idList.size()==0) {
			throw new RuntimeException("请选择项");
		}
		IrModel irModel=irModelService.getById(idList.get(0));
		String tableName=(String)paraMap.get("table_name");
		String name=(String)paraMap.get("table_name");
		
		String jsonContent=irModel.getJsonContent();
		ObjectMapper objectMapper=new ObjectMapper();
		try {
			JsonNode jsonNode=objectMapper.readTree(jsonContent);
			ObjectNode objectNode=(ObjectNode)jsonNode;
			objectNode.put("tableName", tableName);
			objectNode.put("name", name);
			String newJsonContent=objectMapper.writeValueAsString(objectNode);
			
			IrModel newModel=new IrModel();
			newModel.setTableName(tableName);
			newModel.setName(name);
			newModel.setJsonContent(newJsonContent);
			newModel.setModuleType(irModel.getModuleType());
			newModel.setModelType(irModel.getModelType());
			irModelService.insert(newModel);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		dataSearch();
	}
}
